{- This file is part of funbot.
 -
 - Written in 2015 by fr33domlover <fr33domlover@rel4tion.org>.
 -
 - ♡ Copying is an act of love. Please copy, reuse and share.
 -
 - The author(s) have dedicated all copyright and related and neighboring
 - rights to this software to the public domain worldwide. This software is
 - distributed without any warranty.
 -
 - You should have received a copy of the CC0 Public Domain Dedication along
 - with this software. If not, see
 - <http://creativecommons.org/publicdomain/zero/1.0/>.
 -}

module FunBot.Sources.WebListener
    ( webListenerSource
    )
where

import FunBot.Sources.WebListener.Client (dispatchClient)
import FunBot.Sources.WebListener.GitLab (dispatchGitLab)
import FunBot.Sources.WebListener.Gogs (dispatchGogs)
import FunBot.Types
import Network.HTTP (Request (..), RequestMethod (..))
import Network.HTTP.Listen (run)
import Network.IRC.Fun.Bot.State (askEnvS)
import Network.URI (uriPath)

listener push pushMany request = do
    case (uriPath $ rqURI request, rqMethod request) of
        ("/gogs", POST)   -> dispatchGogs push pushMany request
        ("/gitlab", POST) -> dispatchGitLab push pushMany request
        ("/client", POST) -> dispatchClient push pushMany request
        _ -> do
            putStrLn "Web listener source: Unrecognized request received:"
            print request
    return Nothing

webListenerSource _config env push pushMany _mkLogger = do
    putStrLn "Bot: Web listener source listening to HTTP requests"
    run (webHookSourcePort env) $ listener push pushMany
